﻿@COFE ?= {}
Link = COFE.Link
Entry = COFE.Entry
EntryList = COFE.EntryList

# MODEL - Represents a COFEWS EntryList.
# events - fetched, error
# variables - status = notready, working, ready, error
class EntryList extends Spine.Model
  # url - url the entrylist loaded from, e.g. a /search or /entry/{guid}/list
  # entryIds - Id of the entries in the entry list, entry are saved separately.
  # status - current status of the entry list (notready -> working -> ready)
  @configure 'EntryList', 'url', 'entryIds', 'status', 'links'

  @constructor : ->
    @entries = []

  init : =>        
    @status = "notready" 
  
  # Construct an EntryList from a COFE path (e.g. {cofe}\obj)
  EntryList.fromPath = (path) ->
    EntryList.fromUrl(Link.fromPath(path).url)  

  # Construct an EntryList from a url, which returns a COFEWS EntryList obj in json.
  EntryList.fromUrl = (url) ->   
    elist = EntryList.findByAttribute('url', url) #Look from cache
    if elist isnt null 
    then elist.regenerate()
    else EntryList.init({ url : url, links : {} })

  # Construct from a link
  EntryList.fromLink = (link) -> 
    EntryList.fromUrl(link.url)
  
  # Construct from Json
   EntryList.fromJson = (data, url) ->
     elist = EntryList.init({ url : url, links : {} })
     elist.refresh(data)
     elist

  # If cached, regenerate @entries (a list of Entry) from @entryIds (a list of Entry Ids)
  regenerate : =>
    @entries = (for entryId in @entryIds
       Entry.fromId(entryId))
    @status = "ready"
    @

  # If not cached, after a success fetch operation, create entries from json.
  # then save to cache, and raise fetched event.
  refresh : (data) ->
    @type = data.type
    
    @entries = (for entryData in data.entries 
       Entry.fromJson(entryData))
    
    #Sort entry list.  
    @entries.sort((a,b) -> a.compare(b)) 

    #Add links
    for link in data.links
      linkObj = Link.fromJson(link)
      @links[linkObj.rel] = linkObj


    @entryIds = (for entryData in @entries 
       entryData.id)
    @status = "ready"
    @save()
    
    @trigger("fetched", @)  
  
  # Get the @url, and calls @refresh if success, trigger error if fails.
  fetch : =>  
    @status = "working"
    $.getJSON(@url)
      .success((xhr, s, e) =>
        @refresh(xhr)
      )
      .error((xhr, s, e) => 
        @status = "error"
        @trigger("error", @, xhr.responseText)
      )

COFE.EntryList = EntryList